/**
 * 
 */
package com.door.erp.sevice.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.door.erp.dao.GenerateNumberDao;
import com.door.erp.dao.base.GenericDao;
import com.door.erp.model.GenerateNumber;
import com.door.erp.sevice.GenerateNumberService;
import com.door.erp.sevice.base.GenericServiceImpl;

/**
 * @author xiaolongwei@gmail.com
 * 
 * 
 */
@Service("generateNumberService")
public class GenerateNumberServiceImpl extends
		GenericServiceImpl<GenerateNumber, Long> implements
		GenerateNumberService {
	@Resource(name = "generateNumberDao", type = GenerateNumberDao.class)
	private GenerateNumberDao generateNumberDao;

	@Override
	public GenericDao<GenerateNumber, Long> getDao() {
		return this.generateNumberDao;
	}

	@Override
	public synchronized String generateNum(String suffix) {
		if (StringUtils.isBlank(suffix)) {
			suffix = "D";
		}
		String number = "";
		String dayId = suffix + getDateString(); 
		int count = 0;
		List<GenerateNumber> generateNumbers = this.generateNumberDao
				.getHibernateTemplate().find(
						"from GenerateNumber where dayId = '" + dayId+"'");
		if (generateNumbers != null && generateNumbers.size() > 0) {
			GenerateNumber generateNumber = generateNumbers.get(0);
			count = generateNumber.getCount();
			count++;
			generateNumber.setCount(count);
			this.generateNumberDao.modify(generateNumber);
		} else {
			GenerateNumber generateNumber = new GenerateNumber();
			generateNumber.setDayId(dayId);
			count = 1;
			generateNumber.setCount(count);
			this.generateNumberDao.add(generateNumber);
		}
		if (count < 10) {
			number += dayId + "0000" + count;
		} else if (count < 100) {
			number += dayId + "000" + count;
		} else if (count < 1000) {
			number += dayId + "00" + count;
		} else if (count < 10000) {
			number += dayId + "0" + count;
		}
		return number;
	}

	public static String getDateString() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String dateString = sdf.format(new Date());
		return dateString;

	}
	// public static void main(String[] args) {
	// System.out.println(GenerateNumberServiceImpl.getDateString());
	// }
}
